package com.rain.rainspringboot3.encryption.util;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;

public class RSAKeyGenerator {
    
    public static void main(String[] args) {
        try {
            // 生成RSA密钥对
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048); // 密钥长度
            KeyPair keyPair = keyPairGenerator.generateKeyPair();
            
            // 获取公钥和私钥
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            
            // 转换为Base64编码字符串
            String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
            String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());
            
            // 输出结果
            System.out.println("===== RSA Public Key =====");
            System.out.println(wrapWithPEM(publicKeyStr, "PUBLIC KEY"));
            System.out.println("\n===== RSA Private Key =====");
            System.out.println(wrapWithPEM(privateKeyStr, "PRIVATE KEY"));
            
            // 或者以你代码中的格式输出（用|分隔）
            System.out.println("\n===== Key Pair (Separated by |) =====");
            System.out.println(publicKeyStr + "|...................|" + privateKeyStr);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 将Base64字符串包装成PEM格式
     */
    private static String wrapWithPEM(String key, String type) {
        StringBuilder sb = new StringBuilder();
        sb.append("-----BEGIN ").append(type).append("-----\n");
        
        // 每64个字符换行
        for (int i = 0; i < key.length(); i += 64) {
            int end = Math.min(i + 64, key.length());
            sb.append(key.substring(i, end)).append("\n");
        }
        
        sb.append("-----END ").append(type).append("-----");
        return sb.toString();
    }
}
